<?php
namespace Api\Controller;
use Think\Controller;
class CardController extends CommonController {
    public function index(){
        if (isset($_GET['pageNum'])) {
            $page = I('pageNum');
            $page = (int)$page * 10;
        } else {
            $page = 0;
        }
        $map = array();
        //会员日查询
        if(I('zhou')!='no'){
            $map['_string'] = '  ((is_week = 1 and week_'.I('zhou') . '= 1) or (is_day = 1 and FIND_IN_SET('.ltrim(I('hao'),'0').',days)))';
        }
        $map['s.wid'] = session('wid');
        $map['s.status'] = [['eq',1],['eq',2],'or'];
        $map['s.is_shield'] = 0;//屏蔽
        $map['c.status'] = 1;
        $list = M("shop")->alias('s')
            ->join('tp_shop_card_yh c on c.shop_id = s.shop_id')
            ->where($map)
            ->where(['s.join_end_time' => ['gt', date('Y-m-d H:i:s', time())]])
            ->order("s.is_top desc,c.sort_num desc,s.is_dao asc,s.last_time desc")
            ->limit(0, $page)
            ->select();
        foreach ($list as $key => $value) {
            // is_pin is_kan is_qiang 活动项目
            $goods = M('goods')->where(['shop_id' => $value['shop_id']])->select();
            foreach ($goods as $kk => $vv) {
                if ($vv['is_pin']) {
                    $list[$key]['has_pin'] = 1;
                }
                if ($vv['is_kan']) {
                    $list[$key]['has_kan'] = 1;
                }
                if ($vv['is_qiang']) {
                    $list[$key]['has_qiang'] = 1;
                }
            }
        }
        foreach ($list as $key => $value) {
            $list[$key]['type'] = trim($value['type']);
            //商户距离计算
            if (I('la') != 'undefined' && I('lo') != 'undefined') {
                if ($value['latitude'] && $value['longitude']) {
                    $earthRadius = 6367000;
                    $lat1 = (float) I('la');//纬度
                    $lng1 = (float) I('lo');//经度
                    $lat2 = (float) $value['latitude'];
                    $lng2 = (float) $value['longitude'];
                    $lat1=($lat1* pi()) / 180;
                    $lng1=($lng1* pi()) / 180;
                    $lat2=($lat2* pi()) / 180;
                    $lng2=($lng2* pi()) / 180;
                    $calcLongitude = $lng2-$lng1;
                    $calcLatitude = $lat2-$lat1;
                    $stepOne = pow(sin($calcLatitude/2),2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude/2),2);
                    $stepTwo = 2* asin(min(1, sqrt($stepOne)));
                    $distance = round($earthRadius*$stepTwo);
                    if ($distance < 1000) {
                        $list[$key]['r_distance'] = $distance.'米';
                    } else {
                        $distance = $distance / 1000;
                        $list[$key]['r_distance'] = round($distance, 2).'公里';
                    }
                } else {
                    $list[$key]['r_distance'] = '';
                }
            } else {
                $list[$key]['r_distance'] = '';
            }
        }
        foreach ($list as $k => $v) {
            $eq['shop_id'] = $v['shop_id'];
            $eq['is_pin'] = 1;
            $eq['status'] = 1;
            $list[$k]['has_pin'] = M("Goods")->where($eq)->find();

            $eq1['shop_id'] = $v['shop_id'];
            $eq1['is_pin'] = 0;
            $eq1['is_kan'] = 1;
            $eq1['status'] = 1;
            $list[$k]['has_kan'] = M("Goods")->where($eq1)->find();

            $eq2['shop_id'] = $v['shop_id'];
            $eq2['is_qiang'] = 1;
            $eq2['status'] = 1;
            $list[$k]['has_qiang'] = M("Goods")->where($eq2)->find();

            $eq3['shop_id'] = $v['shop_id'];
            $eq3['status'] = 1;
            $list[$k]['has_coupon'] = M("Coupon")->where($eq3)->find();

            //免预约
            $eq4['shop_id'] = $v['shop_id'];
            $eq4['yuyue'] = 1;
            $info = M("shop_card_yh")->where($eq4)->find();
            $list[$k]['has_mian'] = ($info['yuyue']==1?1:0);

            //同城折扣
            $eq5['shop_id'] = $v['shop_id'];
            $eq5['discount'] = ['gt',0];
            $list[$k]['has_zhe'] = M("shop_card_yh")->where($eq5)->find()?1:0;

            //同城特惠信息
            $eq6['shop_id'] = $v['shop_id'];
            $info3 = M("shop_card_yh")->where($eq6)->find();
            $list[$k]['discount_remark'] = $info3['discount_remark'];
            $list[$k]['discount'] = $info3['discount'];
        }
        $this->ajaxReturn($list);
    }

    public function getshop()
    {
        //推荐活动商品
        $whereH['a.is_kan']   = ['neq', 0];
        $whereH['a.is_pin']   = ['neq', 0];
        $whereH['a.is_qiang'] = ['neq', 0];
        $whereH['_logic']     = 'or';
        $whereHuo['_complex'] = $whereH;
        $whereHuo['a.wid']    = session('wid');
        $whereHuo['a.status'] = 1;
        $listHuo =  M("Goods")->alias('a')
            ->field('a.*, b.join_end_time, b.cate')
            ->join('tp_shop b on a.shop_id = b.shop_id')
            ->where($whereHuo)
            ->where(['b.join_end_time' => ['gt', date('Y-m-d H:i:s', time())]])
            ->order("last_time desc,remark desc")
            ->limit(0, 8)
            ->select();
        $this->ajaxReturn($listHuo);
    }

    //同城卡首页优惠信息
    public function getyhInfo()
    {
        $arr['shop_count'] = M('shop_card_yh')->where(['wid'=>session('wid'),'status'=>1])->count();
        $arr['member_count'] = M('card_log')->where(['wid'=>session('wid'),'is_pay'=>1,'end_time' => ['gt', date('Y-m-d H:i:s', time())]])->count();
        $this->ajaxReturn($arr);
    }
    //获取时间
    public function getdate()
    {
        $arr= [];
        for($i=0;$i<31;$i++) {
            $arr[$i]['hao'] = date('d',strtotime('+'.$i.' days',time()));
            if($i==0){
                $arr[$i]['zhou']  = '今天';
            }
            elseif($i== 1){
                $arr[$i]['zhou']  = '明天';
            }
            elseif($i == 2){
                $arr[$i]['zhou']  = '后天';
            }else{
                $arr[$i]['zhou'] = '周'.mb_substr("日一二三四五六",date('w',strtotime('+'.$i.' days')),1,'utf-8');
            }
            $arr[$i]['select'] = 0;
            $arr[$i]['zhou_num'] = date('w',strtotime('+'.$i.' days'));

        }
        $arr2[]=['zhou'=>date('m')."月",'hao'=>"全部",'select'=>1,'zhou_num'=>'no'];
        $arr = array_merge($arr2,$arr);
        $this->ajaxReturn($arr);

    }
    //开通同城卡
    public function openCard()
    {
        $map['wid'] = session('wid');
        $wechat = M("Wechat")->where($map)->find();
        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];
        //查出同城卡信息
        $map2['id'] = $_POST['cardid'];
        $info = M("card")->where($map2)->find();

        //只能开更高级别的卡
        $eq['c.wid'] = session('wid');
        $eq['c.is_pay'] = 1;
        $eq['c.end_time'] =['gt',date("Y-m-d H:i:s",time())];
        $eq['c.openid'] = I('openid');
        $card = M('card_log')->alias('c')->join('tp_card f on f.id = c.cid')->where($eq)->order('f.days desc')->find();
        if($card['days'] >= $info['days']){
            $arr = array("err_code"=>400,"err_msg"=>"您已开通".$card['title']);
            $this->ajaxReturn($arr);
        }

        $log = M('card_log')->where(['wid'=>session('wid'),'is_pay'=>1,'create_time'=>['lt',date("Y-m-d H:i:s",strtotime('-120 seconds'))]])
                ->order('create_time desc')
                ->find();
        if($log){
            $no = $log['no']+1;
        }else{
            $no = '201800001';
        }
        $eq1['wid'] = session('wid');
        $eq1['is_pay'] = 1;
        $eq1['end_time'] =['gt',date("Y-m-d H:i:s",time())];
        $days = M('card_log')->where($eq1)->order('id desc')->find();
        //开过卡就相加
        if($days['end_time']){
            $end =date('Y-m-d H:i:s', strtotime('+'.$info['days'].'days',strtotime($days['end_time'])));
        }else{
            $end =date('Y-m-d H:i:s',strtotime('+'.$info['days'].'days',time()));
        }

        //card_log表信息
        $data['wid'] = $info['wid'];
        $data['cid'] = $info['id'];//同城卡id
        $data['openid'] = $_POST['openid'];
        $data['end_time'] = $end;
        $data['create_time'] = date("Y-m-d H:i:s",time());
        $data['no'] = $no;
        $data['out_trade_no'] = $this->build_order_no();
        $data['is_pay'] = 0;

        if (!$logcard_id = M("card_log")->add($data)) {
            $arr = array("err_code" => 400, "err_msg" => "网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }

        $url = "https://" . $_SERVER['HTTP_HOST'] . U("Notify/openCard");
        // echo $url;
        vendor('Weixinpay.WxPayJsApiPay');
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        if (!$data['remark']) {
            $data['remark'] = "智联同城";
        }
        $input->SetBody($data['remark']);
        $input->SetAttach('开通同城卡');
        $input->SetOut_trade_no($data['out_trade_no']);
        $input->SetTotal_fee(($info['price'] * 100));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        // $input->SetGoods_tag("test3");
        $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($_POST['openid']);
        $input->SetAppid($appid);
        $input->SetMch_id($mch_id);

        try {
            $wxorder = \WxPayApi::unifiedOrder($input, $key);
        } catch (Exception $e) {
            $arr = array("err_code" => 400, "err_msg" => $e->getMessage() . $data['pay_money']);
            $this->ajaxReturn($arr);
        }
        if ($wxorder['return_code'] == "FAIL") {
            $arr = array("err_code" => 400, "err_msg" => $wxorder['return_msg'] . $data['pay_money']);
            $this->ajaxReturn($arr);
        }
        try {
            $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
        } catch (Exception $e) {
            $arr = array("err_code" => 400, "err_msg" => $e->getMessage());
            $this->ajaxReturn($arr);
        }
        //积分产生
        $pro = M('credit_setint')->where(['wid' => $info['wid']])->find();
        $credit = $info['price'] * $pro['tc_card'];
        addCredit($_POST['openid'], $credit, $logcard_id, $info['wid'], 1);

        echo $jsApiParameters;
    }
    //获取 店铺会员卡的页面设计
    public function getCardAddForm(){
        if($_GET['id']){
            switch ($_GET['type']) {

                default:
                    $res = $this->getEditForm();
                    break;
            }
        }else{
            $pics = array();
            $res['add_url'] = "https://www.58zltc.com/api.php/Card/add";
            $form[] = array('type'=>'text', 'title'=>'会员卡名称', 'name'=>'title');
            $form[] = array('type'=>'number', 'title'=>'发行数量', 'name'=>'stock');
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'text', 'title'=>'卡片等级名称', 'name'=>'level_name');
            $form[] = array('type'=>'number', 'title'=>'卡片等级', 'name'=>'level');
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'pic', 'title'=>'卡片图片', 'name'=>'pic', 'num'=>1, 'pic'=>$pics);
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'textarea', 'title'=>'卡片简介', 'name'=>'remark');
            $res['form'] = $form;
        }
        $res['index_url'] = "/pages/mine/shop/card/card";
        $this->ajaxReturn($res);
    }

    //查看编辑页
    // 获取商品编辑表单
    private function getEditForm(){
        $map['id'] = $_GET['id'];
        $info = M("shop_card")->where($map)->find();
        $pics = explode(',', $info['pic']);
        $res['add_url'] = "https://www.58zltc.com/api.php/Card/add/id/{$_GET['id']}";
        $form[] = array('type'=>'text', 'title'=>'会员卡名称', 'name'=>'title', 'value'=>$info['title']);
        $form[] = array('type'=>'number', 'title'=>'发行数量', 'name'=>'stock', 'value'=>$info['stock']);
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'text', 'title'=>'卡片等级名称', 'name'=>'level_name','value'=>$info['level_name']);
        $form[] = array('type'=>'number', 'title'=>'卡片等级', 'name'=>'level','value'=>$info['level']);
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'pic', 'title'=>'卡片图片', 'name'=>'pic', 'num'=>1, 'pics'=>$pics);
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'textarea', 'title'=>'卡片简介', 'name'=>'remark', 'value'=>$info['remark']);
        $res['form'] = $form;
        return $res;
    }


    //获取 店铺会员卡的的特权页
    public function getRightsAddForm(){
        if($_GET['id']){
            switch ($_GET['type']) {

                default:
                    $res = $this->getRightsEditForm();
                    break;
            }
        }else{
            $pics = array();
            $res['add_url'] = "https://www.58zltc.com/api.php/Card/addRights";
            $form[] = array('type'=>'text', 'title'=>'名称', 'name'=>'title');
            $form[] = array('type'=>'text', 'title'=>'描述', 'name'=>'content');
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'pic', 'title'=>'显示图标', 'name'=>'pic', 'num'=>1, 'pic'=>$pics);
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'number', 'title'=>'排序', 'name'=>'order_num');
            $res['form'] = $form;
        }
        $res['index_url'] = "/pages/mine/shop/card/card";
        $this->ajaxReturn($res);
    }

    //获得添加会员等级
    public function getAddlevel()
    {
        if($_GET['id']){
            switch ($_GET['type']) {

                default:
                    $res = $this->getRightsEditForm();
                    break;
            }
        }else{
            $res['add_url'] = "https://www.58zltc.com/api.php/Card/addLevel";
            $form[] = array('type'=>'text', 'title'=>'名称', 'name'=>'level_name');
            $form[] = array('type'=>'number', 'title'=>'升级金额', 'name'=>'money');
            $res['form'] = $form;
        }
        $res['index_url'] = "/pages/mine/shop/card/level";
        $this->ajaxReturn($res);
    }

    //添加会员等级
    public function addLevel(){
        foreach ($_POST as $key => $value) {
            if (!is_numeric($value) && empty($value)) {
                $arr = array("err_code" => 400, "err_msg" => "请填写全部信息！");
                $this->ajaxReturn($arr);
            }
        }
        //根据卡片的情况是修改还是添加
        $map['wid'] = session('wid');
        $map['shop_id'] = $_GET['id'];
        $map['openid'] = $_POST['openid'];
        if($_GET['id']){
            //$r = M("shop_card")->where($map)->save($_POST);
            $r = M("Shop")->where($map)->save(['credit_set' => $_POST['credit_set']]);
            if($r){
                $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"没有进行任何修改哦！");
                $this->ajaxReturn($arr);
            }
        }else{
            $eq['card_id'] = $_POST['card_id'];//会员卡
            $eq['level_name'] = $_POST['level_name'];//会员卡名称
            $eq['money'] = $_POST['money'];//升级需要满足的金额
            $re = M("shop_card_level")->add($eq);
            if($re){
                $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
                $this->ajaxReturn($arr);
            }
        }
    }

    //查看编辑页
    // 获取商品编辑表单
    private function getRightsEditForm(){
        $map['id'] = $_GET['id'];
        $info = M("shop_card_rights")->where($map)->find();
        $pics = explode(',', $info['img']);
        $res['add_url'] = "https://www.58zltc.com/api.php/Card/add/id/{$_GET['id']}";
        $form[] = array('type'=>'text', 'title'=>'名称', 'name'=>'title', 'value'=>$info['title']);
        $form[] = array('type'=>'text', 'title'=>'描述', 'name'=>'content', 'value'=>$info['content']);
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'pic', 'title'=>'卡片图片', 'name'=>'pic', 'num'=>1, 'pics'=>$pics);
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'number', 'title'=>'排序', 'name'=>'order_num', 'value'=>$info['order_num']);
        $res['form'] = $form;
        return $res;
    }

    //添加会员特权简介
    public function addRights(){
        $eq['wid'] = session('wid');
        $eq['openid'] = $_POST['openid'];
        $eq['shop_id'] = M("Shop")->where($eq)->getField("shop_id");
        foreach ($_POST as $key => $value) {
            if (!is_numeric($value) && empty($value)) {
                $arr = array("err_code" => 400, "err_msg" => "请填写全部信息！");
                $this->ajaxReturn($arr);
            }
        }
        if($_GET['id']){
            $map['wid'] = session('wid');
            $map['id'] = $_GET['id'];
            $map['openid'] = $_POST['openid'];
            $r = M("shop_card_rights")->where($map)->save($_POST);
            if($r){
                $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"没有进行任何修改哦！");
                $this->ajaxReturn($arr);
            }
        }else{
            $mp['wid'] = session('wid');
            $mp['openid'] = $_POST['openid'];
            $_POST['shop_id'] = M("Shop")->where($mp)->getField("shop_id");

            $_POST['wid'] = session('wid');
            $_POST['last_time'] = date("Y-m-d H:i:s");
            $_POST['status'] = 1;

            if(M("shop_card_rights")->add($_POST)){
                $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
                $this->ajaxReturn($arr);
            }
        }
    }

    //查询商铺上传的额会员卡
    public function shopCardRights(){
        if (isset($_GET['pageNum'])) {
            $page = I('pageNum');
            $page = ((int)$page + 1) * 10;
        } else {
            $page = 0;
        }

        $eq['wid'] = session('wid');
        $eq['openid'] = $_GET['openid'];
        $eq['status'] = 1;
        $eq['card_id'] = $_GET['card_id'];
        $rights = M('shop_card_rights')->where($eq) ->limit(0, $page)->select();

        $this->ajaxReturn($rights);
    }



    //添加店铺会员卡
    public function add(){

        foreach ($_POST as $key => $value) {
            if (!is_numeric($value) && empty($value)) {
                $arr = array("err_code" => 400, "err_msg" => "请填写全部信息！");
                $this->ajaxReturn($arr);
            }
        }
        //根据卡片的情况是修改还是添加
        $map['wid'] = session('wid');
        $map['shop_id'] = $_GET['id'];
        $map['openid'] = $_POST['openid'];
        if($_GET['id']){
            //$r = M("shop_card")->where($map)->save($_POST);
            $r = M("Shop")->where($map)->save(['credit_set' => $_POST['credit_set']]);
            if($r){
                $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"没有进行任何修改哦！");
                $this->ajaxReturn($arr);
            }
        }else{
            $eq['wid'] = session('wid');
            $eq['openid'] = $_POST['openid'];
            $_POST['shop_id'] = M("Shop")->where($eq)->getField("shop_id");
            $_POST['wid'] = session('wid');
            $_POST['create_time'] = date("Y-m-d H:i:s");
            $_POST['status'] = 1;

            if(M("shop_card")->add($_POST)){
                $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
                $this->ajaxReturn($arr);
            }
        }
    }
    /*删除会员卡*/
    public function del(){
        $map['wid'] = session('wid');
        $map['id'] = $_GET['id'];
        $map['openid'] = $_GET['openid'];
        $new['status'] = 0;

        if(M("shop_card")->where($map)->save($new)){
            $arr = array("err_code"=>0, "err_msg"=>"删除成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }

    //查询商铺上传的额会员卡
    public function shopCard(){
        if (isset($_GET['pageNum'])) {
            $page = I('pageNum');
            $page = ((int)$page + 1) * 10;
        } else {
            $page = 0;
        }
        $res = array();
        $map = array();
        $map['wid'] = session('wid');
        $map['status'] = 1;
        if($_GET['openid']){
            $map['openid'] = $_GET['openid'];
        }

       $shop = M("Shop")->where($map)->find();
        $eq['wid'] = session('wid');
        $eq['status'] = 1;
        $eq['shop_id'] = $shop['shop_id'];
        if($_GET['card_id']){
            $eq['id'] = $_GET['card_id'];
            //查询会员数
            $where['wid'] = session('wid');
            $where['card_id'] = $_GET['card_id'];
            $user_acount = M('Shop_mycard')->where($where)->count('id');
            //充值金额
            $recharge_money = M('shop_recharge_log')->alias('l')
                ->join('tp_shop_mycard as m on l.mycard_id=m.id')
                ->where(array('l.state'=>1,'l.type'=>1))->sum('l.money');
            $integral_money = M('shop_meal_log')->alias('l')
                ->join('tp_shop_mycard as m on l.mycard_id=m.id')
                ->where(array('l.state'=>1))->sum('l.money');
            $allmoney = $recharge_money+$integral_money;
            $res['user_acount'] = $user_acount;
            $res['allmoney'] = $allmoney;
        }

        $list = M("shop_card")
            ->where($eq)
            ->select();
        $res['list'] = $list;
        $res['shop'] = $shop;
        $this->ajaxReturn($res);
    }


/*
 * 更具会员卡添加相应的套餐
 * */

    public function getMealAddForm(){
        if($_GET['id']){
            switch ($_GET['type']) {

                default:
                    $res = $this->getMealEditForm();
                    break;
            }
        }else {
            //查询服务商品
            $eq['wid'] = session('wid');
            $eq['openid'] = $_GET['openid'];
            $eq['status'] = 1;
            $eq['card_id'] = $_GET['card_id'];
            $goods = M('shop_card_good')->where($eq)->select();

            $res['add_url'] = "https://www.58zltc.com/api.php/Card/addMeal";
            $form[] = array('type' => 'text', 'title' => '套餐名称', 'name' => 'title');
            $form[] = array('type'=>'digit', 'title'=>'套餐价格', 'name'=>'price');
            $form[] = array('type'=>'digit', 'title'=>'会员价格', 'name'=>'user_price');
           // $form[] = array('type'=>'digit', 'title'=>'赠送积分', 'name'=>'credit');
            $form[] = array('type' => 'top');

            foreach($goods as $k=>$row){
                $goods[$k]['img_url'] = M('goods')->where(array('id'=>$row['good_id']))->getField("img_url");
            }

            $form[] = array('type' => 'textarea', 'title' => '套餐简介', 'name' => 'remark');
            $res['form'] = $form;
            $res['goods'] = $goods;
        }
        $res['index_url'] = "/pages/mine/shop/card/card";
        $this->ajaxReturn($res);
    }

    /*
     * 获取修改套餐的展示页面
     * */
    public function getMealEditForm(){

            //查询服务商品
            $eq['wid'] = session('wid');
            $eq['openid'] = $_GET['openid'];
            $eq['status'] = 1;
            $eq['card_id'] = $_GET['card_id'];
            $goods = M('shop_card_good')->where($eq)->select();
            $map['id'] = $_GET['id'];
        //查询该套餐
            $meal = M('shop_card_meal')->where($map)->find();
            if ($meal) {
                $m_url = "https://www.58zltc.com/api.php/Card/addMeal/id/".$meal['id'];
            } else {
                $m_url = "https://www.58zltc.com/api.php/Card/addMeal";
            }
            $res['add_url'] = $m_url;
            $form[] = array('type' => 'text', 'title' => '套餐名称', 'name' => 'title','value'=>$meal['title']);
            $form[] = array('type'=>'digit', 'title'=>'套餐价格', 'name'=>'price','value'=>$meal['price']);
            $form[] = array('type'=>'digit', 'title'=>'会员价格', 'name'=>'user_price','value'=>$meal['user_price']);
           // $form[] = array('type'=>'digit', 'title'=>'赠送积分', 'name'=>'credit','value'=>$meal['credit']);
            $form[] = array('type' => 'top');



            $form[] = array('type' => 'textarea', 'title' => '套餐简介', 'name' => 'remark','value'=>$meal['remark']);
            $res['form'] = $form;
            //将选中的商品
            $goodid_arr = explode(',',$meal['goods_id']);
            foreach($goods as $k=>$row){
                foreach($goodid_arr as $id){
                    if($row['id'] == $id){
                    $goods[$k]['checked'] = 1;
                    }
                }

                $goods[$k]['img_url'] = M('goods')->where(array('id'=>$row['good_id']))->getField("img_url");
            }

            $res['goods'] = $goods;

            $res['index_url'] = "/pages/mine/shop/card/card";
            $this->ajaxReturn($res);
    }

    /*
     *添加套餐
     * */
    public function addMeal(){

        $eq['wid'] = session('wid');
        $eq['openid'] = $_POST['openid'];
        $eq['shop_id'] = M("Shop")->where($eq)->getField("shop_id");
        foreach ($_POST as $key => $value) {
            if (!is_numeric($value) && empty($value)) {
                $arr = array("err_code" => 400, "err_msg" => "请填写全部信息！");
                $this->ajaxReturn($arr);
            }
        }
        $_POST['goods_id'] = substr($_POST['goods'], 0, -1);
        //查询总次数
        $count = M('Shop_card_good')->where(array('id'=>array('in',$_POST['goods_id'])))->sum('num');
        //单价
        $_POST['pay_money'] = floor($_POST['user_price']/$count * 100) / 100;
        if($_GET['id']){
            $map['wid'] = session('wid');
            $map['id'] = $_GET['id'];
            $map['openid'] = $_POST['openid'];
            $r = M("shop_card_meal")->where($map)->save($_POST);
            if($r){
                $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"没有进行任何修改哦！");
                $this->ajaxReturn($arr);
            }
        }else{
            $card = M('shop_card')->where($eq)->find();
            if (empty($card)) {
                $arr = array("err_code" => 400, "err_msg" => "该会员卡不存在！");
                $this->ajaxReturn($arr);
            }

            $mp['wid'] = session('wid');
            $mp['openid'] = $_POST['openid'];
            $_POST['shop_id'] = M("Shop")->where($mp)->getField("shop_id");

            $_POST['wid'] = session('wid');
            $_POST['create_time'] = date("Y-m-d H:i:s");
            $_POST['status'] = 1;

            if(M("shop_card_meal")->add($_POST)){
                $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
                $this->ajaxReturn($arr);
            }
        }
    }
    //获取套餐记录
    public function getMealList(){
        if (isset($_GET['pageNum'])) {
            $page = I('pageNum');
            $page = ((int)$page + 1) * 10;
        } else {
            $page = 0;
        }

        $eq['wid'] = session('wid');
        $eq['openid'] = $_GET['openid'];
        $eq['status'] = 1;
        $map['s.shop_id'] = M("Shop")->where($eq)->getField("shop_id");
        $eq['card_id'] = $_GET['card_id'];
        $eq['type'] = $_GET['status'];
        $meals = M('shop_card_meal')->where($eq) ->limit(0, $page)->select();
        foreach($meals as $key=>$row){
            $goods_id = explode(',',$row['goods_id']);
            //查询添加的相关的服务商品
            foreach($goods_id as $good_id){
                $map = array();
                $map['s.wid'] = session('wid');
                $map['s.status'] = 1;
                $map['s.card_id'] = $_GET['card_id'];
                $map['s.id'] = $good_id;
                $good =  M("shop_card_good")->alias('s')
                    ->field('s.*, g.img_url')
                    ->join('tp_goods g on s.good_id = g.id')
                    ->where($map)
                    ->find();
                $meals[$key]['goods'][] = $good;
            }
        }
        $this->ajaxReturn($meals);
    }
    //删除套餐
    public function delMeal(){
        $map['wid'] = session('wid');
        $map['id'] = $_GET['id'];
        $map['openid'] = $_GET['openid'];
        $new['status'] = 0;

        if(M("shop_card_meal")->where($map)->save($new)){
            $arr = array("err_code"=>0, "err_msg"=>"删除成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }

    //删除会员特权简介
    public function delRight(){
        $map['wid'] = session('wid');
        $map['id'] = $_GET['id'];
        $map['openid'] = $_GET['openid'];
        $new['status'] = 0;

        if(M("shop_card_rights")->where($map)->save($new)){
            $arr = array("err_code"=>0, "err_msg"=>"删除成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }

    //展示添加服务商品的页面
    public function getGoodAddForm(){


        if($_GET['id']){
            switch ($_GET['type']) {

                default:
                    $res = $this->getGoodEditForm();
                    break;
            }
        }else {
            $eq['wid'] = session('wid');
            $eq['openid'] = $_GET['openid'];
            $eq['status'] = 1;
            $top_arr = M("goods")->where($eq)->order("id asc")->getField('title', true);
            $id_arr = M("goods")->where($eq)->order("id asc")->getField('id', true);
            $form[] = array('type' => 'picker1', 'title' => '平台商品', 'name' => 'good_id'
            , 'range' => $top_arr
            , 'id' => $id_arr
            , 'value' => 0);


            $res['add_url'] = "https://www.58zltc.com/api.php/Card/addGood";
            $form[] = array('type' => 'text', 'title' => '商品名称', 'name' => 'title');
            $form[] = array('type' => 'hidden', 'title' => '卡片id', 'name' => 'card_id', 'value' => $_GET['card_id']);
            $form[] = array('type' => 'number', 'title' => '数量', 'name' => 'num');
            $form[] = array('type' => 'top');
            $form[] = array('type' => 'digit', 'title' => '价格', 'name' => 'price');
            $res['form'] = $form;
        }
         $res['index_url'] = "/pages/mine/shop/card/card";
         $this->ajaxReturn($res);
    }

    //添加修改商品页面展示
    private function getGoodEditForm(){
        $eq['wid'] = session('wid');
        $eq['openid'] = $_GET['openid'];
        $eq['status'] = 1;
        $top_arr = M("goods")->where($eq)->order("id asc")->getField('title', true);
        $id_arr = M("goods")->where($eq)->order("id asc")->getField('id', true);
        $form[] = array('type' => 'picker1', 'title' => '平台商品', 'name' => 'good_id'
        , 'range' => $top_arr
        , 'id' => $id_arr
        , 'value' => 0);
        $map['id'] = $_GET['id'];
        $info = M("shop_card_good")->where($map)->find();
        $res['add_url'] = "https://www.58zltc.com/api.php/Card/addGood/id/{$_GET['id']}";
        $form[] = array('type'=>'text', 'title'=>'商品名称', 'name'=>'title', 'value'=>$info['title']);
        $form[] = array('type'=>'number', 'title'=>'数量', 'name'=>'stock', 'value'=>$info['num']);
        $form[] = array('type'=>'top');
        $form[] = array('type' => 'digit', 'title' => '价格', 'name' => 'price','value'=>$info['price']);
        $res['form'] = $form;
        return $res;
    }

    //添加服务商品
    public function addGood(){
        $mp['wid'] = session('wid');
        $mp['openid'] = $_POST['openid'];
        $mp['status'] = 1;
        $good = M("goods")->where($mp)->order("id asc")->getField('id',true);

        $eq['wid'] = session('wid');
        $eq['openid'] = $_POST['openid'];
        $eq['shop_id'] = M("Shop")->where($eq)->getField("shop_id");
        foreach ($_POST as $key => $value) {
            if (!is_numeric($value) && empty($value)) {
                $arr = array("err_code" => 400, "err_msg" => "请填写全部信息！");
                $this->ajaxReturn($arr);
            }
        }
        $_POST['good_id'] = $good[$_POST['good_id']];
        $good = M("goods")->where(array('id'=>$_POST['good_id']))->find();
        $_POST['img_url'] = $good['img_url'];

        if($_GET['id']){
            $map['wid'] = session('wid');
            $map['id'] = $_GET['id'];
            $map['openid'] = $_POST['openid'];
            $r = M("shop_card_good")->where($map)->save($_POST);
            if($r){
                $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"没有进行任何修改哦！");
                $this->ajaxReturn($arr);
            }
        }else{
            $card = M('shop_card')->where($eq)->find();
            if (empty($card)) {
                    $arr = array("err_code" => 400, "err_msg" => "该会员卡不存在！");
                    $this->ajaxReturn($arr);
            }

            $card_good = M('shop_card_good')->where(array('good_id'=>$_POST['good_id']))->find();
            if($card_good){
                $arr = array("err_code" => 400, "err_msg" => "已添加该商品！");
                $this->ajaxReturn($arr);
            }
            $mp['wid'] = session('wid');
            $mp['openid'] = $_POST['openid'];
            $_POST['shop_id'] = M("Shop")->where($mp)->getField("shop_id");

            $_POST['wid'] = session('wid');
            $_POST['create_time'] = date("Y-m-d H:i:s");
            $_POST['status'] = 1;

            if(M("shop_card_good")->add($_POST)){
                $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
                $this->ajaxReturn($arr);
            }
        }
    }
    //查询会员卡添加的服务商品
    public function shopCardGood(){
        if (isset($_GET['pageNum'])) {
            $page = I('pageNum');
            $page = ((int)$page + 1) * 10;
        } else {
            $page = 0;
        }

        $map = array();
        $map['s.wid'] = session('wid');
        $map['s.status'] = 1;
        if($_GET['openid']){
            //查询该店铺的id
            $eq['wid'] = session('wid');
            $eq['openid'] = $_GET['openid'];
            $map['s.shop_id'] = M("Shop")->where($eq)->getField("shop_id");
        }

        if($_GET['card_id']){
            $map['s.card_id'] = $_GET['card_id'];
        }
        $list = M("shop_card_good")->alias('s')
            ->field('s.*, g.img_url')
            ->join('tp_goods g on s.good_id = g.id')
            ->where($map)
            ->order("create_time desc")
            ->limit(0, $page)
            ->select();
        $this->ajaxReturn($list);

    }
//    删除会员卡对应的服务商品
    public function delGood(){
        $map['wid'] = session('wid');
        $map['id'] = $_GET['id'];
        $map['openid'] = $_GET['openid'];
        $new['status'] = 0;

        if(M("shop_card_good")->where($map)->save($new)){
            $arr = array("err_code"=>0, "err_msg"=>"删除成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }

    //添加会员充值优惠的表单
    public function addRechargeForm(){
        if($_GET['id']){
            switch ($_GET['type']) {

                default:
                    $res = $this->getRechargeEditForm();
                    break;
            }
        }else{
            $res['add_url'] = "https://www.58zltc.com/api.php/Card/addRecharge";
            $form[] = array('type'=>'text', 'title'=>'名称', 'name'=>'title');
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'digit', 'title'=>'充值金额', 'name'=>'money');
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'digit', 'title'=>'赠送金额', 'name'=>'get_money');
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'textarea', 'title'=>'简介', 'name'=>'content');
            $res['form'] = $form;
        }
        $res['index_url'] = "/pages/mine/shop/card/card";
        $this->ajaxReturn($res);


        $eq['wid'] = session('wid');
        $eq['openid'] = $_GET['openid'];
        $eq['shop_id'] = M("Shop")->where($eq)->getField("shop_id");
        $card = M('shop_card')->where($eq)->find();

        $res['add_url'] = "https://www.58zltc.com/api.php/Card/add/id/{$_GET['card_id']}";



        $this->ajaxReturn($res);
    }
    //会员充值优惠编辑页面
    private function getRechargeEditForm(){
        $map['id'] = $_GET['id'];
        $info = M("shop_card_recharge")->where($map)->find();
        $res['add_url'] = "https://www.58zltc.com/api.php/Card/addRecharge/id/".$_GET['id'];
        $form[] = array('type'=>'text', 'title'=>'名称', 'name'=>'title','value'=>$info['title']);
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'digit', 'title'=>'充值金额', 'name'=>'money','value'=>$info['money']);
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'digit', 'title'=>'赠送金额', 'name'=>'get_money','value'=>$info['get_money']);
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'textarea', 'title'=>'简介', 'name'=>'content','value'=>$info['content']);
        $res['form'] = $form;
        return $res;
    }
    //会员充值优惠添加记录
    public function addRecharge(){
        $eq['wid'] = session('wid');
        $eq['openid'] = $_POST['openid'];
        $eq['shop_id'] = M("Shop")->where($eq)->getField("shop_id");
        foreach ($_POST as $key => $value) {
            if (!is_numeric($value) && empty($value)) {
                $arr = array("err_code" => 400, "err_msg" => "请填写全部信息！");
                $this->ajaxReturn($arr);
            }
        }
        if($_GET['id']){
            $map['wid'] = session('wid');
            $map['id'] = $_GET['id'];
            $map['openid'] = $_POST['openid'];
            $r = M("shop_card_recharge")->where($map)->save($_POST);
            if($r){
                $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"没有进行任何修改哦！");
                $this->ajaxReturn($arr);
            }
        }else{
            $mp['wid'] = session('wid');
            $mp['openid'] = $_POST['openid'];
            $_POST['shop_id'] = M("Shop")->where($mp)->getField("shop_id");

            $_POST['wid'] = session('wid');
            $_POST['last_time'] = date("Y-m-d H:i:s");
            $_POST['status'] = 1;

            if(M("shop_card_recharge")->add($_POST)){
                $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
                $this->ajaxReturn($arr);
            }
        }
    }
    //查询会员充值优惠记录
    public function getCardRecharge(){
        if (isset($_GET['pageNum'])) {
            $page = I('pageNum');
            $page = ((int)$page + 1) * 10;
        } else {
            $page = 0;
        }

        $map = array();
        $map['wid'] = session('wid');
        $map['status'] = 1;
        if($_GET['openid']){
            //查询该店铺的id
            $eq['wid'] = session('wid');
            $eq['openid'] = $_GET['openid'];
            $map['shop_id'] = M("Shop")->where($eq)->getField("shop_id");
        }

        if($_GET['card_id']){
            $map['card_id'] = $_GET['card_id'];
        }
        $list = M("shop_card_recharge")
            ->where($map)
            ->order("id desc")
            ->limit(0, $page)
            ->select();
        $this->ajaxReturn($list);
    }
    //删除会员充值优惠记录
    public function delRecharge(){
        $map['wid'] = session('wid');
        $map['id'] = $_GET['id'];
        $map['openid'] = $_GET['openid'];
        $new['status'] = 0;

        if(M("shop_card_recharge")->where($map)->save($new)){
            $arr = array("err_code"=>0, "err_msg"=>"删除成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }

    //添加会员积分获得的比例
    public function addCreditForm(){

        $eq['wid'] = session('wid');
        $eq['openid'] = $_GET['openid'];
        $eq['shop_id'] = M("Shop")->where($eq)->getField("shop_id");
        $card = M('shop_card')->where($eq)->find();
        $shop = M('shop')->where(['shop_id' => $eq['shop_id']])->find();

        $res['add_url'] = "https://www.58zltc.com/api.php/Card/add/id/{$_GET['card_id']}";
        $form[] = array('type' => 'digit', 'title' => '1元对应积分', 'name' => 'credit_set','value'=>$shop['credit_set']);
        $form[] = array('type' => 'top');
        $res['form'] = $form;
        $res['index_url'] = "/pages/mine/shop/card/card";
        $this->ajaxReturn($res);
    }


    public function getOrderWxaCode(){
        $access_token = $this->getAccessToken();

        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
        $post_data = array(
            'scene'=>$_GET['openid'].",".session('wid'),
            'page'=>'pages/shop/hexiao/hexiao'
        );
        $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $res = $this->ihttp_post($url, $json);
        header('Content-type: image/JPEG');
        echo $res;
        // dump($res);
    }
    private function getAccessToken(){
        $map['wid'] = session("wid");
        $info = M("Wechat")->where($map)->find();

        if(date("Y-m-d H:i:s") < $info['token_end_time']){
            return $info['authorizer_access_token'];
        }else{
            $token = $this->get_component_access_token();
            $url = "https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token={$token}";

            $post_data = array(
                "component_appid"=>C("OPEN_APPID"),
                "authorizer_appid"=>$info['appid'],
                "authorizer_refresh_token"=>$info['authorizer_refresh_token']);
            $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
            $res = $this->ihttp_post($url, $json);
            $td = json_decode($res, true);
            if($td['authorizer_access_token']){
                $map['wid'] = $info['wid'];
                $data['authorizer_access_token'] = $td['authorizer_access_token'];
                $data['authorizer_refresh_token'] = $td['authorizer_refresh_token'];
                $data['token_end_time'] = date("Y-m-d H:i:s", time()+$td['expires_in']-60);
                M("Wechat")->where($map)->save($data);
                return $td['authorizer_access_token'];
            }else{
                // dump($td);
                // $this->error($td['errmsg']);
                // $this->reAuth();
                exit("网络忙！");
            }
        }
    }

    private function get_component_access_token(){
        $token = S("component_access_token");
        if($token){
            return $token;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";

        $post_data = array(
            "component_appid"=>C("OPEN_APPID"),
            "component_appsecret"=>C("OPEN_APPSECRET"),
            "component_verify_ticket"=>S("component_verify_ticket"));
        $json = json_encode($post_data, JSON_UNESCAPED_UNICODE);
        $res = $this->ihttp_post($url, $json);
        $td = json_decode($res, true);
        if($td['component_access_token']){
            S("component_access_token", $td['component_access_token'], $td['expires_in'] - 120);
            return $td['component_access_token'];
        }else{
            return false;
        }
    }

    //会员优惠券管理
    public function getAddCouponForm(){
        $res['index_url'] = "/pages/mine/shop/coupon/list";

        if($_GET['id']){
            $map['id'] = $_GET['id'];
            $info = M("shop_card_coupon")->where($map)->find();
            $pics = explode(',', $info['pics']);
            $res['add_url'] = "https://www.58zltc.com/api.php/Card/cardCouponAdd/id/{$_GET['id']}";

            $form[] = array('type'=>'text', 'title'=>'优惠券名称', 'name'=>'title', 'value'=>$info['title']);
            $form[] = array('type'=>'digit', 'title'=>'优惠金额', 'name'=>'coupon_price', 'value'=>$info['coupon_price']);
            $form[] = array('type'=>'number', 'title'=>'发放数量', 'name'=>'stock', 'value'=>$info['stock']);
            $form[] = array('type'=>'text', 'title'=>'一句话简介', 'name'=>'coupon_remark', 'value'=>$info['coupon_remark']);
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'pic', 'title'=>'优惠券图片', 'name'=>'pics', 'num'=>2, 'pics'=>$pics);
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'textarea', 'title'=>'优惠券简介', 'name'=>'content', 'value'=>$info['content']);
        }else{
            $pics = array();
            $res['add_url'] = "https://www.58zltc.com/api.php/Card/cardCouponAdd";

            $form[] = array('type'=>'text', 'title'=>'优惠券名称', 'name'=>'title');
            $form[] = array('type'=>'number', 'title'=>'优惠金额', 'name'=>'coupon_price');
            $form[] = array('type'=>'number', 'title'=>'发放数量', 'name'=>'stock');
            $form[] = array('type'=>'text', 'title'=>'一句话简介', 'name'=>'coupon_remark');
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'pic', 'title'=>'优惠券图片', 'name'=>'pics', 'num'=>2, 'pics'=>$pics);
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'textarea', 'title'=>'优惠券简介', 'name'=>'content');
        }
        $res['form'] = $form;
        $this->ajaxReturn($res);
    }
    public function cardCouponAdd(){
        foreach ($_POST as $key => $value) {
            if(!is_numeric($value) && empty($value)){
                $arr = array("err_code"=>400,"err_msg"=>"请填写全部信息！");
                $this->ajaxReturn($arr);
            }
        }
        if($_GET['id']){
            $map['id'] = $_GET['id'];
            $map['wid'] = session('wid');
            $map['openid'] = $_POST['openid'];
            if(M("shop_card_coupon")->where($map)->save($_POST)){
                $arr = array("err_code"=>0, "err_msg"=>"修改成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"没有进行任何修改哦！");
                $this->ajaxReturn($arr);
            }
        }else{
            $eq['wid'] = session('wid');
            $eq['openid'] = $_POST['openid'];
            $_POST['shop_id'] = M("Shop")->where($eq)->getField("shop_id");
            $_POST['wid'] = session('wid');
            $_POST['create_time'] = date("Y-m-d H:i:s");
            $_POST['status'] = 1;

            if(M("shop_card_coupon")->add($_POST)){
                $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
                $this->ajaxReturn($arr);
            }
        }

    }
    //获得优惠券列表
    public function getCoupon(){
        $map = array();
        $map['wid'] = session('wid');
        $map['status'] = 1;
        if($_GET['openid']){
            $map['openid'] = $_GET['openid'];
        }
        if($_GET['shop_id']){
            $map['shop_id'] = $_GET['shop_id'];
        }
        if($_GET['card_id']){
            $map['card_id'] = $_GET['card_id'];
        }
        $list = M("shop_card_coupon")->where($map)->order("last_time desc")->select();
        foreach ($list as $key => $value) {
            $list[$key]['buy_percent'] = ($value['buy_num']/$value['stock'])*100;
        }
        $this->ajaxReturn($list);
    }

    public function delCoupon(){
        $map['wid'] = session('wid');
        $map['id'] = $_GET['id'];
        $map['openid'] = $_GET['openid'];

        $new['status'] = 0;
        if(M("shop_card_coupon")->where($map)->save($new)){
            $arr = array("err_code"=>0, "err_msg"=>"删除成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }
    //关联其他商家
    public function linkShop(){
        //查询开会员卡的其他的店铺
        $map['wid'] = session('wid');
        $map['openid'] = $_GET['openid'];
        $shop_id = M("Shop")->where($map)->getField("shop_id");
        $map['id'] = $_GET['id'];
        //查找该会员卡
        $cards = M('Shop_card')->where($map)->find();
        $linkShop = explode(',',$cards['linkshop']);
        $eq['c.wid'] = session('wid');
        $eq['c.shop_id'] = array('neq',$shop_id);
        $eq['c.status'] = 1;
        $list['list'] = M('Shop_card')
            ->field('c.*,s.logo_url,s.name')
            ->alias('c')
            ->join('tp_shop as s on c.shop_id=s.shop_id')
            ->where($eq)->select();
        foreach($list['list'] as $k=>$card){
            if(in_array($card['id'],$linkShop)){
                $list['list'][$k]['check'] = 0;
            }else{
                $list['list'][$k]['check'] = 1;
            }
        }
        $eq1['wid'] = session('wid');
        $eq1['shop_id'] = array('neq',$shop_id);
        $eq1['status'] = 1;
        $list['count'] = M('Shop_card')->where($eq1)->count('id');
        $this->ajaxReturn($list);
    }
    //关联选中的店铺
    public function linkCard(){
        $data['wid'] =session('wid');
        $data['id'] = $_GET['card_id'];
        $card = M('Shop_card')->where($data)->find();

        $linkShop = explode(',',$card['linkshop']);
        if(in_array($_GET['id'],$linkShop)){
            $arr = array("err_code"=>400,"err_msg"=>"已关联！");
            $this->ajaxReturn($arr);
        }
        if(empty($card['linkshop'])){
            $change['linkshop'] = $_GET['id'];
        }else{
            $change['linkshop'] = $card['linkshop'].','.$_GET['id'];
        }


        $r = M('Shop_card')->where($data)->save($change);
        if($r){
            $arr = array("err_code"=>0,"err_msg"=>"操作成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }

    //取消关联
    public function excel(){
        $data['wid'] =session('wid');
        $data['id'] = $_GET['card_id'];
        $card = M('Shop_card')->where($data)->find();

        $linkShop = explode(',',$card['linkshop']);
       foreach($linkShop as $k=>$row){
            if($row == $_GET['id']){
                unset($linkShop[$k]);
            }
       }
        $change['linkshop'] = implode(',',$linkShop);

        $r = M('Shop_card')->where($data)->save($change);
        if($r){
            $arr = array("err_code"=>0,"err_msg"=>"操作成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }
    //推荐奖设置
    public function Recommend(){
        //查询

        $eq['wid'] = session('wid');
        $eq['card_id'] = $_GET['card_id'];
        $eq['status'] = 1;
        $list['meal'] = M('shop_card_meal')->where($eq)->select();
        foreach($list['meal'] as $k=>$meal){
            $goodid_arr = explode(',',$meal['goods_id']);
            $list['meal'][$k]['good'] = M('shop_card_good')->where(array('id'=>array('in',$meal['goods_id']),'status'=>1))->select();

        }
        //获取充值的表单
        $res['add_url'] = "https://www.58zltc.com/api.php/Card/AddRecommend";
        $form[] = array('type' => 'top');
        $form[] = array('type' => 'digit', 'title' => '分享奖励', 'name' => 'money');
        $form[] = array('type' => 'top');
        $res['form'] = $form;
        $res['index_url'] = "/pages/mine/shop/card/card";
        $list['form'] = $res;
        $this->ajaxReturn($list);
    }
    public function AddRecommend(){
        $map['id'] = $_POST['card_id'];
        $map['wid'] = session('wid');
        $change['recommend'] = $_POST['money'];
        $change['recommend_meal'] = $_POST['meal_id'];
        $r = M('Shop_card')->where($map)->save($change);
        if($r){
            $arr = array("err_code"=>0,"err_msg"=>"操作成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }

}